<template>
  <view class="page-container" :style="listHeightStylePage">
    <u-navbar :title="title" placeholder @leftClick="leftClick" :border="false" :shadow="true"></u-navbar>
    <!-- 导航栏 -->
    <view class="topdiv" style="height: 160rpx; flex-shrink: 0;">
      <up-tabs :list="tabs" :current="currentTab" :scrollable="false" @click="clickTabs"></up-tabs>
      <view class="view-search" @click="search">
        <u-search placeholder="请输入关键字" v-model="keyword" :showAction="false" style="pointer-events:none;"
          :disabled="true"></u-search>
      </view>
    </view>

    <scroll-view :refresher-background="'transparent'" :scroll-top="scrollTop" :style="listHeightStyle"
      class="apply-menu" scroll-y="true" :refresher-enabled="true" :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh" @scrolltolower="loadMore">
      <view v-for="(item, index) in list" :key="index" class="list-item" @click="goJumpTo(item)">
        <view class="list-li">
          <view class="unread-dot" v-if="item.is_read == '1'"></view>
          <!-- 标题 -->
          <view class="apply-info-title">
            <view class="title">{{ item.title }}</view>
            <view class="hui">{{ item.create_time }}</view>
          </view>

          <!-- 申请人信息 -->
          <view class="applicant">申请人: {{ item.create_name }}</view>

          <!-- 提示信息 -->
          <view class="tip" v-for="(r, idx) in item.tip" :key="idx">{{ r }}</view>

          <!-- 时间信息 -->
          <!-- <view class="time-info">
              <view v-if="item.create_time">发起时间: {{ item.create_time }}</view>
              <view v-if="item.end_time">完成时间: {{ item.end_time }}</view>
            </view> -->

          <!-- 分割线 -->
          <!-- <up-divider></up-divider> -->

          <!-- 审批状态 -->
          <view class="apply-info">
            <view class="in-author">
              <image class="head-img" :src="item.head_img"></image> 由{{ item.create_name }}提交
            </view>
            <view class="status" :class="getStatusClass(item.status)">
              {{ item?.approver }}{{ getStatusText(item.status) }}
               
            </view>
          </view>


        </view>
      </view>

      <!-- 加载中提示 -->
      <view v-if="loading" class="loading-text">
        加载中...
      </view>

      <!-- 没有更多数据提示 -->
      <view v-if="noMore" class="no-more-text">
        没有更多数据了
      </view>

    </scroll-view>

    <!-- 搜索弹出层 -->
    <up-popup :show="show" mode="bottom" @close="show = false" @open="show = true">
      <view class="popup">
        <view style="margin-top: 40rpx;">
          <view class="popup-content">
            <text class="span">关键字：</text>
            <u--input class="input-first" placeholder="请输入关键字" border="surround" v-model="keyword"></u--input>
          </view>
          <view class="popup-content">
            <text class="span">单据类型：</text>
            <view @click="typeShow = true" style="display: inline-block;">
              <u--input class="input" :disabled="true" placeholder="请选择单据类型" border="surround"
                v-model="typeName"></u--input>
            </view>
          </view>
          <view class="popup-content">
            <text class="span">审批状态：</text>
            <view @click="stateShow = true" style="display: inline-block;">
              <u--input class="input" placeholder="请选择审批状态" border="surround" v-model="stateName"></u--input>
            </view>
          </view>
          <view class="popup-content">
            <text class="span">提交审批时间：</text>
            <view @click="startShow = true" style="display: inline-block;">
              <u--input class="input" placeholder="请选择提交审批时间" border="surround" v-model="startTimeString"></u--input>
            </view>
          </view>
          <view class="popup-content">
            <text class="span">完成审批时间：</text>
            <view @click="endShow = true" style="display: inline-block;">
              <u--input class="input" placeholder="请选择完成审批时间" border="surround" v-model="endTimeString"></u--input>
            </view>
          </view>
        </view>
        <view style="text-align: center; margin-top: 100rpx;display: flex;">
          <u-button class="custom-btn" text="清空" @click="clean()"></u-button>
          <u-button class="custom-btn primary-btn" type="primary" text="确定" @click="sure()"></u-button>
        </view>

      </view>
    </up-popup>
    <!-- 单据弹出层 -->
    <u-picker :show="typeShow" :columns="typeColumns" keyName="formName" @confirm="confirmType"
      @cancel="typeShow = false"></u-picker>
    <!-- 审批状态弹出层 -->
    <u-picker :show="stateShow" :columns="stateColumns" keyName="label" @confirm="confirmState"
      @cancel="stateShow = false"></u-picker>
    <!-- 提交审批时间日历 -->
    <u-calendar :show="startShow" :mode="mode" @confirm="confirmStart" @close="startShow = false"></u-calendar>
    <!-- 完成审批时间日历 -->
    <up-calendar :show="endShow" :mode="mode" @confirm="confirmEnd" @close="endShow = false"></up-calendar>
  </view>
</template>

<script>
import apply from "@/apis/cloud/apply.js";
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
export default {
  mixins: [MescrollMixin],
  data () {
    return {
      scrollTop: 0,
      currentTab: 0,
      title: '',
      active: '',
      tabs: [{
        name: "待处理"
      }, {
        name: "已处理"
      }, {
        name: "已发起"
      }, {
        name: "我收到的"
      }],
      upOption: {
        page: {
          size: 10 // 每页数据的数量,默认10
        },
        noMoreSize: 10, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
        empty: {
          tip: '暂无更多...'
        }
      },
      total: 0,
      queryParams: {
        pageSize: 6,
        pageNum: 1
      },
      list: [],
      show: false,
      keyword: '',
      typeShow: false,
      typeColumns: [],
      typeName: '',
      typeId: 0,
      stateShow: false,
      stateColumns: [
        [{
          label: '全部',
          state: 0,
        },
        {
          label: '审批完成',
          state: 1,
        },
        {
          label: '审批中',
          state: 2,
        },
        {
          label: '已撤销',
          state: 3,
        },
        ]
      ],
      stateName: '',
      stateId: '',
      startShow: false,
      startTimeString: '',
      mode: 'range',
      endShow: false,
      endTimeString: '',
      start: '',
      starts: '',
      end: '',
      ends: '',
      loading: false,
      noMore: false,
      isRefreshing: false,
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      topHeight: 0,
      listHeightStylePage: {},
    }
  },
  onShow () {
    const modalTitleGet = uni.getStorageSync('modalTitleGet') || false
    if (modalTitleGet) {
      this.refreshList();
      uni.removeStorageSync('modalTitleGet')
    }
  },
  created () {
    // #ifdef H5
    this.listHeightStylePage = {
      height: `${window.innerHeight}px`,
    };
    // #endif

    // #ifdef APP-PLUS
    this.listHeightStylePage = {
      height: `100vh`,
    };
    // #endif
    let app = uni.getSystemInfoSync();
    this.topHeight = app.statusBarHeight;
  },
  mounted () {
    this.getInfo();
    this.getTypeColumns();
    this.calculateListHeight()
  },
  methods: {
    calculateListHeight () {
      const windowHeight = window.innerHeight; // 视口高度
      const topHeight = this.topHeight || 0; // 顶部安全高度
      const navbarHeight = 44; // 导航栏高度（假设为 44px）
      const tabsHeight = 88;
      // console.log('windowHeight',windowHeight)
      // #ifdef APP-PLUS
      this.listHeightStyle = {
        overflowY: 'hidden',
        height: '1330rpx',
      };
      // #endif

      // #ifdef H5
      const listHeight = windowHeight - topHeight - navbarHeight - tabsHeight;
      this.listHeightStyle = {
        height: `${listHeight}px`,
        overflowY: 'hidden'
      };
      // #endif
    },
    // 获取状态文本
    getStatusText (status) {
      const statusMap = {
        1: '审批中',
        2: '审批同意',
        3: '审批驳回',
        4: '审批撤销',
      };
      return statusMap[status] || '';
    },

    // 获取状态样式类
    getStatusClass (status) {
      return `status-${status}`;
    },
    onRefresh () {
      this.isRefreshing = true; // 开始刷新
      this.refreshList().finally(() => {
        this.isRefreshing = false; // 停止刷新
      });
    },
    loadMore () {
      if (this.loading || this.noMore) return;
      this.queryParams.pageNum++;
      this.getInfo();
    },
    refreshList () {
      this.list = [];
      this.queryParams.pageNum = 1;
      this.noMore = false;
      return this.getInfo();
    },
    leftClick () {
      uni.navigateBack({
        delta: 1
      });
      // uni.reLaunch({
      // 	url: '/pages/workspace/home/index',
      // })
    },
    clickTabs (item) {
      switch (item.name) {
        case "待处理":
          this.active = 1;
          break;
        case "已处理":
          this.active = 2;
          break;
        case "已发起":
          this.active = 3;
          break;
        case "我收到的":
          this.active = 4;
          break;
      }
      this.title = item.name;
      this.list = [];
      this.queryParams.pageNum = 1;
      this.noMore = false;


      this.scrollTop = 0;
      this.$nextTick(() => {
        this.scrollTop = 1;
        this.$nextTick(() => {
          this.scrollTop = 0;
        });
      });
      this.getInfo();
    },
    async getTypeColumns () {
      const result = await apply.getFormTypes({});
      if (result.status > 0) {
        this.typeColumns = [result.data];
      }
    },
    async getInfo () {
      // 显示加载框
      uni.showLoading({
        title: '加载中...'
      });
      if (this.loading) return;
      this.loading = true;
      // state: 0,
      // type: 0,
      try {
        const result = await apply.getApplyOrder({
          active: this.active,
          page: this.queryParams.pageNum,
          row: this.queryParams.pageSize,
          keywords: this.keyword,
          type: this.typeId,
          state: this.stateId,
          start: this.start,
          starts: this.starts,
          end: this.end,
          ends: this.ends
        });

        if (result.status > 0) {
          this.list = this.queryParams.pageNum === 1 ? result.data : [...this.list, ...result.data];
          this.total = result.total;

          if (this.list.length >= this.total) {
            this.noMore = true;
          }
        } else {
          this.loading = false;
          this.noMore = true;
          this.list = []
          uni.showToast({
            title: '加载失败',
            icon: 'error',
          });
        }
      } catch (err) {
        this.loading = false;
        this.noMore = true;
        this.list = []
        uni.showToast({
          title: '加载失败',
          icon: 'error',
        });
        console.error('请求失败', err);
      } finally {
        // 隐藏加载框
        uni.hideLoading();
        this.loading = false;
      }
    },
    mescrollInit (mescroll) {
      this.mescroll = mescroll;
    },
    /*上拉加载的回调*/
    upCallback (page) {
      this.list = [];
      this.queryParams.pageNum = page.num; // 页码, 默认从1开始
      this.queryParams.pageSize = page.size; // 页码, 默认从1开始
      this.getInfo();
    },
    /*若希望重新加载列表,只需调用此方法即可(内部会自动page.num=1,再主动触发up.callback)*/
    reloadList () {
      this.mescroll.resetUpScroll();
    },
    search () {
      this.show = true;
    },
    confirmType (e) {
      this.typeName = e.value[0].formName;
      this.typeId = e.value[0].id;
      this.typeShow = false;
    },
    confirmState (e) {
      this.stateName = e.value[0].label;
      this.stateId = e.value[0].state;
      this.stateShow = false;
    },
    confirmStart (e) {
      this.startTimeString = e[0] + " 至 " + e[e.length - 1];
      this.start = e[0];
      this.end = e[e.length - 1];
      this.startShow = false;
    },
    confirmEnd (e) {
      this.endTimeString = e[0] + " 至 " + e[e.length - 1];
      this.starts = e[0];
      this.ends = e[e.length - 1];
      this.endShow = false;
    },
    clean () {
      this.keyword = '';
      this.typeName = '';
      this.stateName = '';
      this.startTimeString = '';
      this.endTimeString = '';
      this.typeId = 0
      this.stateId = 0
    },
    sure () {
      this.show = false;
      this.list = [];
      this.getInfo();
    },
    goJumpTo (item) {
      uni.navigateTo({
        url: '/pages/apply/oaList/applyOrderDetail?id=' + item.id
      });
      item.is_read = null
    }
  },
  onLoad (option) {
    uni.$off('refreshApplyList')
    this.title = option.title;
    this.active = option.active;
    // 根据 active 值找到 tabs 中对应的索引
    const tabIndex = this.tabs.findIndex(tab => tab.name === option.title);
    if (tabIndex !== -1) {
      this.currentTab = tabIndex;
    }
    uni.$on('refreshApplyList', () => {
      this.refreshList();
    });
  }
}
</script>

<style lang="scss" scoped>
page {
  overflow-x: hidden;
  overflow-y: hidden;
  /* 禁止页面滚动 */
  background-color: #F3F4F5;
}

.apply-info-title {
  display: flex;
  justify-content: space-between; // 让标题和时间分布在两端
  align-items: center; // 垂直居中对齐
  margin-bottom: 10rpx;

  .title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    flex: 1; // 占据剩余空间
    white-space: nowrap; // 禁止换行
    overflow: hidden; // 超出部分隐藏
    text-overflow: ellipsis; // 超出部分显示省略号
    margin-right: 20rpx; // 和时间保持一定间距
  }

  .hui {
    font-size: 30rpx;
    color: #767676;
    flex-shrink: 0; // 防止时间被压缩
  }
}

/* 申请人信息 */
.applicant {
  font-size: 26rpx;
  color: #767676;
  margin-bottom: 10rpx;
}

/* 提示信息 */
.tip {
  font-size: 26rpx;
  color: #767676;
  margin-bottom: 10rpx;
  word-break: break-all; // 允许单词内断行
  white-space: normal; // 允许多行显示
  overflow: hidden; // 防止内容溢出容器
}

/* 时间信息 */
.time-info {
  display: flex;
  justify-content: space-between;
  font-size: 26rpx;
  color: #767676;
  margin-bottom: 10rpx;
}

.apply-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 25rpx 0 25rpx;
}

.apply-info .in-author {
  display: flex;
  align-items: center;
}

/* 头像 */
.head-img {
  width: 60rpx;
  height: 60rpx;
  object-fit: fill;
  border-radius: 12rpx;
  margin-right: 5rpx;
}

/* 审批状态 */
.status {
  margin-top: 10rpx;
  font-size: 28rpx;
  font-weight: bold;
}

/* 动态状态样式 */
.status-1 {
  color: #3c9cff; // 审批中
}

.status-2 {
  color: #5ac725; // 审批同意
}

.status-3 {
  color: #f56c6c; // 审批驳回
}

.status-4 {
  color: #909399; // 审批撤销
}


/* 加载中和无更多数据提示 */
.loading-text,
.no-more-text {
  margin-top: 20rpx;
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 28rpx;
}

.custom-btn {
  width: 320rpx;
  align-items: center;
  /* 垂直居中 */
  justify-content: center;
  /* 水平居中 */
  padding: 10px 20px;
  /* 调整内边距 */
  height: 80rpx;
  /* 固定高度 */
  line-height: normal;
  /* 避免文字偏移 */

  &.primary-btn {
    background-color: #007aff;
    /* 自定义主色调 */
    color: white;
    /* 文字颜色 */
  }
}

.page-container {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  /* 禁止页面滚动 */
}


::v-deep .u-tabs__wrapper {
  background-color: white;
}

.view-search {
  background-color: white;

  .search {
    padding: 10rpx 0rpx 10rpx 0rpx;
  }

  ::v-deep .u-search__content {
    margin: 20rpx 20rpx 20rpx 20rpx !important;
  }
}

.list-li {
  position: relative;
  //margin-left: 30rpx;
  //margin-right: 30rpx;
  padding: 25rpx;
  padding-bottom: 10rpx;

  .unread-dot {
    position: absolute;
    left: 10rpx;
    top: 10rpx;
    width: 5px;
    height: 5px;
    background-color: #f56c6c;
    border-radius: 50%;
    z-index: 1;
  }
}

::v-deep .u-divider {
  margin: 10px 0px 0px 0px;
}

.apply-menu {
  background-color: #f2f2f2;
  padding-top: 30rpx;
  overflow-y: auto;

}

.list-item {
  border-radius: 20rpx;
  margin: 20rpx;
  background-color: #fff;
}

.topdiv {
  //z-index: 1;
  //display: block;
  //width: 100%;
  //height: 100px !important;
  //background-color: white ;;
  flex-shrink: 0;
  /* 固定高度，不被压缩 */
  background-color: white;
  z-index: 1;
  /* 防止被内容覆盖 */

  .view-search {
    background-color: white;

    ::v-deep .u-search__content {
      background-color: white;
    }
  }
}

.popup {
  padding: 36rpx 0rpx;

  .popup-content {
    margin: 20rpx 10rpx 20rpx 40rpx;
  }
}

.input-first {
  border: 1rpx solid #dadbde;
  display: inline-block;
  width: 420rpx;

  background-color: white !important;
}

.input {
  border: 1rpx solid #dadbde;
  display: inline-block;
  width: 420rpx;
  pointer-events: none;
  background-color: white !important;
}

.span {
  display: inline-block;
  width: 230rpx;
}

.btn {
  display: inline-block;
  width: 280rpx;
  margin-right: 50rpx;
}

.btnS {
  display: inline-block;
  width: 280rpx;
}
</style>
